//
//  NewsReaderAppDelegate.m
//  NewsReader
//
//  Created by blacksun on 10-10-17.
//  Copyright __MyCompanyName__ 2010. All rights reserved.
//

#import "NewsReaderAppDelegate.h"
#import "RootViewController.h"
#import "LoadingViewController.h"


@implementation NewsReaderAppDelegate

@synthesize window;
@synthesize navigationController,user,rootViewController,isGFW;
@synthesize loadingViewController;
@synthesize operationQueue;
@synthesize loadSections;
@synthesize networkState;


#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    
	//创建数据库表
	[SqlUtil createFeedTable];
	
	[window addSubview:self.loadingViewController.view];
    [window makeKeyAndVisible];
	
	NSOperationQueue *temp = [[[NSOperationQueue alloc] init] autorelease];
	self.operationQueue = temp;
	[temp release];
	NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(deleteDataThreeDaysAgo) object:nil];
	[operationQueue addOperation:operation];
	[operation release];

	/*
	NSString *path = [[NSBundle mainBundle] pathForResource:kDefaultSectionConfig ofType:@"txt"];
	NSArray *defaultSections = [[NSArray alloc] initWithContentsOfFile:path];
	self.loadSections = defaultSections;
		
	[defaultSections release];
	
	[self performSelector:@selector(updateSectionImage:) withObject:[NSString stringWithFormat:@"%d",0] afterDelay:5];
    */return YES;
}

-(void)updateSectionImage:(NSString *) indexStr{
	ImageDownloader *downloader = [[ImageDownloader alloc] init];
	downloader.delegate = self;
	downloader.identifier = indexStr;
	downloader.imageUrl = @"http://www.google.com.hk/intl/zh-CN/images/logo_cn.png";
	[downloader startDownload];
	[downloader release];
	
}

- (void)imageLoaded:(UIImage *)image forIdentify:(NSObject *)identifier{
	if (!image) 
		return;
	NSData *imageData = UIImagePNGRepresentation(image);
	NSString *name =  [[NSString alloc] initWithFormat:@"%@.png",identifier];
	NSString *imagePath = [self dataFilePath:name];
	[imageData writeToFile:imagePath atomically:YES];
	[name release];
	
	int index = [(NSString *)identifier intValue];
	if (index <[self.loadSections count]-1) {
		[self updateSectionImage:[NSString stringWithFormat:@"%d",index+1]];
	}else {
		self.loadSections = nil;
	}
	

}





-(void)deleteDataThreeDaysAgo{
	NSDate *currentDate = [NSDate date];
	NSDate *threeDaysAgo = [NSDate dateWithTimeIntervalSince1970:[currentDate timeIntervalSince1970]-user.saveFeedDays*24*60*60];
	[SqlUtil deleteFeedsAndItsContentsEalierThen:threeDaysAgo];

	/*NSFileManager *fileManager = [NSFileManager defaultManager];
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentPath = [paths objectAtIndex:0];
	NSArray *files = [fileManager contentsOfDirectoryAtPath:documentPath error:nil];
	for (NSString *path in files) {
		if ([path rangeOfString:kUserFile].length != 0 || [path rangeOfString:kSqlFilePath].length != 0 ) {
			continue;
		}
		NSString *fullPath = [documentPath stringByAppendingPathComponent:path];
		NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:fullPath error:NULL];
		NSDate *modifyDate = [fileAttributes objectForKey:NSFileModificationDate];
		if ([modifyDate compare:threeDaysAgo] == NSOrderedAscending) {
			[fileManager removeItemAtPath:fullPath error:NULL];
		}

	}*/
	
}




- (void)applicationDidEnterBackground:(UIApplication *)application {
	self.user.needUpdateSections = YES;
    [self archiverUser:self.user];
	self.isGFW= NO;
	
	[self.navigationController popToRootViewControllerAnimated:NO];
	[self.navigationController.view removeFromSuperview];

	[self.loadingViewController viewWillAppear:NO];
	[window addSubview:self.loadingViewController.view];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
	//[appDelegate.window addSubview:appDelegate.navigationController.view];
	
	[self.rootViewController viewDidAppear:YES];
	[self.loadingViewController viewDidAppear:YES];

}

/*
- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     
}*/

/*
- (void)applicationWillTerminate:(UIApplication *)application {
    /*
     Called when the application is about to terminate.
     See also applicationDidEnterBackground:.
     
}*/


#pragma mark -
#pragma mark Memory management
/*
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
}*/


- (void)dealloc {
	[self.rootViewController release];
	[self.navigationController release];
	[self.user release];
	self.loadingViewController=nil;
	[window release];
	[super dealloc];
}


//获取缓存文件的路径
-(NSString *)dataFilePath:(NSString *)fileName{
	NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentDir = [array objectAtIndex:0];
	return [documentDir stringByAppendingPathComponent:fileName];
}
-(void)archiverUser:(User *)aUser{
	NSMutableData *newData = [[NSMutableData alloc] init];
	NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:newData];
	[archiver encodeObject:aUser forKey:kUserDefaultKey];
	[archiver finishEncoding];
	[newData writeToFile:[self dataFilePath:kUserFile] atomically:YES];
	[archiver release];
	[newData release];
}



@end

